{% extends 'admin.phtml' %}

{% block head %}
{% autoescape false %}
{{ js('/js/knockout.validation.min.v0.9.js') }}
{% endautoescape %}

    <script src="/js/elrte/js/jquery-ui-1.8.13.custom.min.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="/js/elrte/css/smoothness/jquery-ui-1.8.13.custom.css" type="text/css" media="screen" charset="utf-8">

    <!-- elRTE -->
    <script src="/js/elrte/js/elrte.min.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="/js/elrte/css/elrte.min.css" type="text/css" media="screen" charset="utf-8">

    <!-- elRTE translation messages -->
    <script src="/js/elrte/js/i18n/elrte.ru.js" type="text/javascript" charset="utf-8"></script>

{% endblock %}

{% block title %}Управление статьями{% endblock %}

{% block body %}

<div class="row" data-bind="with: list">
    <div class="span12">
        <div class="well">
            <a class="btn btn-primary" data-bind="click: $root.gotoAdd"><i class="icon-plus icon-white"></i> Добавить</a>
            <select class="pull-right" data-bind="value: $root.category, options: $root.categories, optionsText: 'title', optionsValue: 'id', optionsCaption: '-- все --'"></select>
        </div>
        <table class="table table-condensed" data-bind="visible: $data.length">
            <thead>
                <tr>
                    <th width="100">Название</th>
                    <th width="100">Рубрика</th>
                    <th>Текст</th>
                    <th width="70">&nbsp;</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: $data">
                <tr>
                    <td data-bind="text: title"></td>
                    <td data-bind="text: category" class="muted"></td>
                    <td data-bind="text: text + '...'" class="muted"></td>
                    <td>
                        <div class="btn-group">
                            <a href="#" data-bind="click: $root.gotoEdit" class="btn btn-small btn-info" title="Редактировать"><i class="icon-pencil icon-white"></i></a>
                            <a href="#" data-bind="click: $root.remove" class="btn btn-small" title="Удалить"><i class="icon-remove"></i></a>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>    

    </div>
</div>

<div class="row" data-bind="with: single">
    <div class="span12">
        <form class="form-horizontal" data-bind="submit: $root.save" method="post">
            <fieldset>
                <legend data-bind="text: $root.legend"></legend>

                {# title #}				
                <div class="control-group" data-bind="css: {error : !title.isValid() && title.isModified()}">
                    <label class="control-label" for="title">Название</label>
                    <div class="controls">
                        <input id="title" type="text" data-bind="value: title" />
                    </div>
                </div>

                {# categories #}
                <div class="control-group" data-bind="css: {error : !category.isValid() && category.isModified()}">
                    <label class="control-label" for="category">Рубрика</label>
                    <div class="controls">
                        <select id="category" data-bind="value: category, options: $root.categories, optionsText: 'title', optionsValue: 'id', optionsCaption: '-- выберите рубрику --'"></select>
                    </div>
                </div>

                {# _text #}
                <div class="control-group" data-bind="css: {error : !_text.isValid() && _text.isModified()}">
                    <label class="control-label" for="_text"></label>
                    <div class="controls">
                        <div id="invited_side" data-bind="html: _text" class="input-xxxlarge" rows="20"></div>
                        {#<p class="help-block">Текст в формате <a href="http://ru.wikipedia.org/wiki/Markdown#.D0.9F.D1.80.D0.B8.D0.BC.D0.B5.D1.80.D1.8B_.D1.81.D0.B8.D0.BD.D1.82.D0.B0.D0.BA.D1.81.D0.B8.D1.81.D0.B0" target="_blank">Markdown</a></p>#}
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">Сохранить</button>
                    <button type="reset" class="btn" data-bind="click: $root.cancel">Отмена</button>
                </div>
            </fieldset>
        </form>
    </div>
</div>

<div class="loadingIndicator">Загрузка...</div>

{% autoescape false %}
<script type="text/javascript">

    ko.validation.init({
        errorMessageClass: 'help-inline'
    })
   
    ko.validation.rules.required.message = 'обязательное поле'

    var Article = function(data) {
        var self = this
        self.id = data.id
        self.title = ko.observable(data.title).extend({required: true})
        self.category = ko.observable(data.category).extend({required: true})
        self._text = ko.observable(data._text).extend({required: true})
    }

    var ArticlesModel = function() {
        var self = this
        self.loadList = function(category) {
            return $.getJSON('/admin/articles/list', {category: category})
        }
        self.loadSingle = function(id) {
            return $.getJSON('/admin/articles/single', {id: id})
        }
        self.save = function(data, callback) {
            $.post('/admin/articles/save', {data: data}, callback)
        }
        self.remove = function(id, callback) {
            $.post('/admin/articles/remove', {id: id}, callback)
        }
        self.loadCategories = function() {
            return $.getJSON('/admin/articles/categories')
        }
    }

    var ArticlesViewModel = function(model) {
        var self = this
        
        self.model = model
        
        self.list = ko.observable()
        self.single = ko.observable()
        self.legend = ko.observable()
        self.category = ko.observable()
        self.categories = ko.observableArray()

        self.gotoList = function() {
            var cid = self.category()
            if (cid)
                location.hash = '/category/' + cid
            else
                location.hash = '/list'
        }

        self.gotoEdit = function(item) {
            self.legend('Редактирование статьи')
            location.hash = '/edit/' + item.id
        }

        self.gotoAdd = function() {
            self.legend('Создание статьи')
            location.hash = '/add'
        }

        self.remove = function(item) {
            if (confirm('Вы уверены, что хотите удалить запись?')) {
                self.model.remove(item.id, self.handleList)
            }
        }

        self.cancel = function() {
            self.gotoList()
        }

        self.save = function() {
            var text = $('#invited_side').elrte('val');
            self.single()._text(text);

            var errors = ko.validation.group(self.single())
            if (errors().length == 0) {
                model.save(self.single(), self.gotoList)
            } else {
                errors.showAllMessages()
            }
        }

        self.handleList = function() {
            var id = (this.params && this.params.id) || self.category()
            $.when(self.model.loadCategories(), self.model.loadList(id))
            .done(function(c, l) {
                self.single(null)
                self.category(id)
                self.categories(c[0])
                self.list(l[0])
            })
        }

        self.handleEdit = function() {
            var id = this.params.id
            $.when(self.model.loadCategories(), self.model.loadSingle(id))
            .done(function(c, s){
                self.list(null)
                self.categories(c[0])
                self.single(new Article(s[0]))
                
                self.runeditor()

            })
        }

        self.runeditor = function(){
            elRTE.prototype.options.toolbars.newToolbar = ['save', 'undoredo', 'style', 'alignment', 'lists', 'images'];
            var opts = {
    				cssClass : 'el-rte',
    				lang     : 'ru',
    				height   : 450,
    				toolbar  : 'newToolbar'
    				// cssfiles : ['css/elrte-inner.css']
    			}
    			$('#invited_side').elrte(opts);
        }
        
        self.handleAdd = function() {
            $.when(self.model.loadCategories())
            .done(function(c){
                self.list(null)
                self.categories(c)
                self.single(new Article({
                    id: -1, title: '', category: self.category()
                }))
                self.runeditor()
            })
        }
        
        self.onCategoryChanged = function() {
            self.gotoList()
        }
        
        Sammy(function() {
            this.get('#/list', self.handleList)
            this.get('#/edit/:id', self.handleEdit)
            this.get('#/add', self.handleAdd)
            this.get('#/category/:id', self.handleList)
        }).run('#/list')
    }
    
    var model = new ArticlesModel()
    var viewModel = new ArticlesViewModel(model)
    viewModel.category.subscribe(viewModel.onCategoryChanged)
    
    ko.applyBindings(viewModel)
    
</script>
{% endautoescape %}
{% endblock %}
